<?php
/**
 * Created by PhpStorm.
 * User: laozhou
 * Date: 2020-03-08
 * Time: 09:27
 */

namespace App\Http\Controllers\Api;


use App\Exceptions\ApiException;
use App\Http\Controllers\Controller;
use App\Http\Response\JsonResult;
use App\Http\Response\ResponseCode;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;

class BaseController extends Controller
{

    protected $queryService   = '';     //查询service
    protected $commandService = '';     //增/更/删 service
    protected $model = '';
    protected $validate = '';           //校验器


    protected function lists_index()
    {
        $request = \request();

        if (empty($this->model)) {
            throw new ApiException(ResponseCode::MODEL_NO_DEFINE);
        }

        if (!empty($this->queryService)) {
            $queryService = app($this->queryService);

            if ( method_exists($queryService,'index') ) {
                return $queryService->index();
            }
        }

        $queryModel = app($this->model);

        $page = $request->input('page',1);
        $limit = $request->input('limit',30);

        $offset = ($page-1)*$limit ;

        $total = $queryModel->count();

        $lists = $queryModel->offset($offset)
            ->limit($limit)
            ->get();

        return ['lists'=>$lists,'count'=>$total];


    }


    public function add(Request $request)
    {
        if ( 'POST' == $request->getMethod() ) {

            //先校验
            $this->validatesData($request,'addRule');

            //如果存在$commandService类的add方法，先调用该方法来添加
            if ( !empty($this->commandService) ) {
                $commandService = app($this->commandService);
                if ( method_exists($commandService,'add') ) {
                    return $commandService->add($request->all());
                }
            }

            //用model来添加
            if (empty($this->model)) {
                throw new ApiException(ResponseCode::MODEL_NO_DEFINE);

            }

            $savedModel = app($this->model);

            try{

                $savedModel->fill($request->all())->save();

                return ;

            }catch (\Exception $exception) {

                throw new ApiException(ResponseCode::EXCEPTION_MESSAGE,[],$exception->getMessage());
            }

        }

        throw new ApiException(ResponseCode::SYSTEM_ERROR_METHOD);
    }

    public function update($id,Request $request)
    {
        if ( 'PUT' == $request->getMethod() ) {

            if (empty($this->model)) {
                throw new ApiException(ResponseCode::MODEL_NO_DEFINE);
            }

            $this->model = app($this->model);
            $info = $this->model->find($id);

            if (empty($info)) {
                throw new ApiException(ResponseCode::DATA_NOT_EXIST);
            }


            //先校验
            $this->validatesData($request,'updateRule');

            //如果存在$commandService类的update方法，先调用该方法来添加
            if ( !empty($this->commandService) ) {
                $commandService = app($this->commandService);
                if ( method_exists($commandService,'update') ) {
                    return $commandService->update($info,$request->all());
                }
            }

            //用model来实现
            foreach ($request->all() as $key => $item) {
                if ( isset($info->$key) ) {
                    $info->$key = $item;
                }
            }

            try{

                $info->save();

                return [];

            }catch (\Exception $exception) {
                throw new ApiException(ResponseCode::EXCEPTION_MESSAGE,[],$exception->getMessage());

            }
        }

        throw new ApiException(ResponseCode::SYSTEM_ERROR_METHOD);


    }

    //查询单个数据，路由 xx/{id}
    public function show($id)
    {
        if ( !empty($this->queryService) ) {

            $queryService = app($this->queryService);

            if ( method_exists($queryService,'show') ) {
                return $queryService->show($id);
            }
        }


        //用model来查询
        if (empty($this->model)) {
            throw new ApiException(ResponseCode::MODEL_NO_DEFINE);
        }

        $model = app($this->model);
        $data = $model->find($id)->toArray();

        //特殊处理一些字段
        if ( isset($data['logo']) ) {
            $data['full_logo'] = config('filesystems.img_domain').$data['logo'];
        }

        return $data;
    }

    //校验数据
    protected function validatesData(Request &$request,$rule='')
    {
        if ( !empty($this->validate) ) {
            $validate = app($this->validate);

            if ( isset($validate->$rule ) ){
                $validator = Validator::make($request->all(), $validate->$rule);

                if ($validator->fails()) {
                    throw new ApiException(ResponseCode::VALIDATE_FAIL,$validator->errors()->all());
                }
            }

        }
    }

    //删除
    public function del($id,Request $request)
    {
        if ( 'DELETE' == $request->getMethod() ) {

            //如果存在$commandService类的update方法，先调用该方法来添加
            if ( !empty($this->commandService) ) {
                $commandService = app($this->commandService);
                if ( method_exists($commandService,'del') ) {
                    return $commandService->del($id,$request->all());
                }
            }

            $this->model = app($this->model);
            $info = $this->model->find($id);

            try{

                $info->delete();

                return [];

            }catch (\Exception $exception) {
                throw new ApiException(ResponseCode::EXCEPTION_MESSAGE,[],$exception->getMessage());

            }

        }

        throw new ApiException(ResponseCode::SYSTEM_ERROR_METHOD);
    }



}